<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/6/15
 * Time: 上午10:00
 */

namespace app\domain;

use app\src\accountScore\action\AccountScoreAction;
use app\src\accountScore\logic\AccountScoreLogic;
use app\src\accountScore\model\AccountScore;
use app\src\base\helper\ConfigHelper;
use app\src\consumehistory\logic\ConsumeHistoryLogic;
use app\src\filiation\action\FiliationAction;
use app\src\filiation\logic\FiliationLogic;
use app\src\hook\PaySuccessHook;
use app\src\order\enum\PayCurrency;
use app\src\payment\action\PaymentAction;
use app\src\platform\emnu\PlatformType;
use app\src\platform\logic\PlatformLogic;
use app\src\profit\action\ProfitAction;
use app\src\profit\enum\ProfitEnum;
use app\src\profit\logic\ProfitLogic;
use app\src\seller\action\SellerAction;
use app\src\seller\logic\SellerLogic;
use app\src\seller\logic\SellerOrderLogic;
use app\src\seller\logic\SellerPromotionLogic;
use app\src\sellerApply\logic\SellerApplyLogic;
use app\src\sellerCategory\logic\SellerCategoryLogic;
use app\src\user\logic\UcenterMemberLogic;
use wordFilter\WordFilter;
use think\Db;
class SellerDomain extends BaseDomain
{
    /**
     * 查询附近商家
     */
    public function queryNearby()
    {
        $this->checkVersion('100');
        $name = $this->_post('name', '');
        $lng = $this->_post('lng', '', 'lng is missing');
        $lat = $this->_post('lat', '', 'lat is missing');
        $cate_id = $this->_post('cate_id');
        $maxDistance = $this->_post('maxDistance', '');
        $city_code = $this->_post('city_code', '');
        $maxDistance = empty($maxDistance) ? false : $maxDistance;
        $city_code = empty($city_code) ? false : $city_code;
        $cate_id = empty($cate_id) ? false : $cate_id;
        $result = (new SellerAction)->getNearby($lng, $lat, $maxDistance, $name, $city_code, $this->getPageParams(),$cate_id);

        $this->returnResult($result);
    }


    /**
     * 查询类目
     */
    public function queryAllCategory()
    {
        $this->checkVersion('100');

        $result = (new SellerCategoryLogic)->queryAllCategory();

        $this->returnResult($result);
    }

    /**
     * 商家详情
     */
    public function detail()
    {
        $this->checkVersion('100');
        $seller_id = $this->_post('seller_id', '', 'seller_id is missing');
        $result = (new SellerAction)->detailInfo($seller_id);

        $this->returnResult($result);
    }

    /**
     * 商家自己添加优惠
     */
    public function addPromotion()
    {
        $this->checkVersion('100');
        $uid = $this->_post('uid', 'uid is missing');
        $seller_id = $this->_post('seller_id', 'seller_id is missing');
        $title = $this->_post('title', 'title is missing');
        $detail = $this->_post('detail', 'detail is missing');
        $img = $this->_post('img', 0);

        $result = (new SellerLogic)->detailInfo($seller_id);
        if(!$result['status']) $this->apiReturnErr($result['info']);
        if($result['info']['seller']['uid']!=$uid){
            $this->apiReturnErr('error uid with this seller');
        }

        //关键词过滤
        $title = (new WordFilter)->filter($title);
        $detail = (new WordFilter)->filter($detail);

        $entity = [
            'seller_id' => $seller_id,
            'title' => $title,
            'detail' => $detail,
            'begin_time' => 0,
            'end_time' => strtotime('2030-01-01'),
            'img' => $img,
            'status' => 0
        ];

        $result = (new SellerPromotionLogic)->addPromotion($seller_id, $entity);
        if($result['status']){
            $this->apiReturnSuc('success');
        }else{
            $this->apiReturnErr($result['info']);
        }

    }

    /**
     * 商家自己删除优惠
     */
    public function delPromotion()
    {
        $this->checkVersion('100');
        $uid = $this->_post('uid', 'uid is missing');
        $seller_id = $this->_post('seller_id', 'seller_id is missing');
        $promotion_id = $this->_post('promotion_id', 'promotion_id is missing');

        $result = (new SellerLogic)->detailInfo($seller_id);
        if(!$result['status']) $this->apiReturnErr($result['info']);
        if($result['info']['seller']['uid']!=$uid){
            $this->apiReturnErr('error uid with this seller');
        }

        $map = ['id' => $promotion_id];
        $result = (new SellerPromotionLogic)->pretendDelete($map);
        if($result['status']){
            $this->apiReturnSuc('success');
        }else{
            $this->apiReturnErr($result['info']);
        }

    }


    /**
     * 个人创业添加商家(申请)
     */
    public function addByPersonalPlatform()
    {
        $this->checkVersion('100');
        $platform_id = $this->_post('platform_id', 'platform_id is missing');
        $name = $this->_post('name', '', 'name is missing');
        $scope = $this->_post('scope', '', 'scope is missing');
        $discount_rate = $this->_post('discount_rate', '', 'discount_rate is missing');
        $rack_back_rate = $this->_post('rack_back_rate', '', 'rack_back_rate is missing');
        $contact_number = $this->_post('contact_number', '', 'contact_number is missing');
        $position = $this->_post('position', '', 'position is missing');
        $bank_card_name = $this->_post('bank_card_name', '', 'bank_card_name is missing');
        $bank_card_no = $this->_post('bank_card_no', '', 'bank_card_no is missing');
        $account_mobile = $this->_post('account_mobile', 'account_mobile is missing');
        $account_psw = $this->_post('account_psw', 'account_psw is missing');
        $logo = $this->_post('logo', 0);
        $main_img = $this->_post('main_img', 0);
        $main_img_small = $this->_post('main_img_small', 0);
        $first_offer = $this->_post('first_offer', '', 'first_offer is missing');
        $first_offer_num = $this->_post('first_offer_num', '', 'first_offer_num is missing');
        $price = $this->_post('price', '', 'price is missing');
        $category_id = $this->_post('category_id', '', 'category_id is missing');


        $result = (new PlatformLogic)->getPlatformInfo($platform_id);
        if(!$result['status']) $this->apiReturnErr($result['info']);

        $platform_info = $result['info'];
        if($platform_info['group_id']!=PlatformType::PERSONAL) $this->apiReturnErr('error platform, can not add seller');

        //判断账号与密码是否正确,没有的账号不用判断
        $map = ['mobile' => $account_mobile, 'country_no' => '+86', 'status' => 1 ];
        $result = (new UcenterMemberLogic)->getInfo($map);
        if(!$result['status']) {
            $this->apiReturnErr($result['info']);
        }
        if(!empty($result['info'])) {
            //检查密码是否正确
            $password = think_ucenter_md5($account_psw,ConfigHelper::getPasswordSalt());
            if($result['info']['password']!=$password) $this->apiReturnErr('账号密码错误');
        }

        $apply_info = [
            'account_mobile' => $account_mobile,
            'account_psw' => $account_psw
        ];

        $entity = [
            'parent_id' => $platform_id,
            'name' => $name,
            'position' => $position,
            'contact_number' => $contact_number,
            'logo' => $logo,
            'main_img' => $main_img,
            'main_img_small' => $main_img_small,
            'synopsis' => '',
            'scope' => $scope,
            'first_offer' => $first_offer,
            'first_offer_num' => $first_offer_num,
            'discount_rate' => $discount_rate,
            'rack_back_rate' => $rack_back_rate,
            'apply_info' => json_encode($apply_info, JSON_UNESCAPED_UNICODE),
            'bank_card_name' => $bank_card_name,
            'bank_card_no' => $bank_card_no,
            'price' => $price,
            'category_id' => $category_id
        ];
        Db::startTrans();
        $result = (new SellerApplyLogic)->addApply($platform_id, $entity);
        if($result['status']){
            Db::commit();
            return $this->apiReturnSuc('success');//不减个创总金额
//            $result = (new PlatformLogic)->getInfo(['id'=>$platform_id]);
//            if(!$result['status'])  $this->apiReturnErr($result['info']);
//            $preferential_money=$result['info']['preferential_money']-$first_offer*$first_offer_num;
//            if($preferential_money<0){
//                Db::rollback();
//                $this->apiReturnErr('优惠金不足');
//            }else{
//                Db::commit();
//                return $this->apiReturnSuc('success');
//            }
        }else{
            Db::rollback();
            $this->apiReturnErr($result['info']);
        }

    }

    /**
     * 申请删除商家
     */
    public function deleteApply()
    {
        //TODO 申请删除商家
    }

    /**
     * 所有下级商家
     */
    public function childAll()
    {
        $this->checkVersion('100');
        $platform_id = $this->_post('platform_id', '', 'platform_id is missing');

        $result = (new SellerLogic)->childAll($platform_id);
        $this->returnResult($result);
    }


    /*
     *获取购买信息
     */
    public function dealBuy(){
        $this->checkVersion('100');
        $seller_id = $this->_post('seller_id', '', 'seller_id is missing');
        $uid = $this->_post('uid', '', 'uid is missing');

        $result = (new SellerLogic)->checkBuy($seller_id,$uid);
        $this->returnResult($result);
    }


    /**
     * 商家下属
     */
    public function sellerMembers(){
        $this->checkVersion('100');
        $seller_id = $this->_post('seller_id', '', 'seller_id is missing');

        $result = (new FiliationLogic())->queryMembers($seller_id);

        $this->returnResult($result);
    }

    /*
     * 获取商家的会员数量与佣金信息
     * type 1个创 2商家
     */
    public function countInfo(){
        $this->checkVersion('100');
        $seller_id = $this->_post('account_id', '', 'account_id is missing');
        $type = $this->_post('account_type','','type is missing');

        $result = (new FiliationAction())->memberAndMoney($seller_id,$type);

        $this->returnResult($result);
    }

    /*
        *
        * types 1上级  2上上级
        */
    public function getrelationship(){
        $this->checkVersion('100');
        $uid = $this->_post('uid', '', 'uid is missing');
        $p = $this->_post('p', '', 'p is missing');
        $type = $this->_post('types', '', 'types is missing');
        if($type==1){
            $type = 'p1';
        }elseif($type==2){
            $type = 'p1_5';
        }else{
            $this->apiReturnErr('类型错误');
        }
        $result = (new FiliationAction())->getrelationship($uid,$type,['curpage'=>$p, 'size'=>10]);

        $this->returnResult($result['info']);

    }

    public function grade(){
        $this->checkVersion('100');
        $seller_id = $this->_post('seller_id', '', 'seller_id is missing');
        $score = $this->_post('score','','score is missing');

        $entity = array();
        $result = (new SellerLogic())->getSellerInfo($seller_id);
        if ($result['status']) {
            $entity['grade'] = $result['info']['grade'] + $score;
            $entity['gn'] = $result['info']['gn'] + 1;
        } else {
            $this->apiReturnErr($result['info']);
        }
        $result = (new SellerLogic())->updateSeller($seller_id, $entity);

        $this->returnResult($result);
    }
    

    /*
     * notify
     */
        public function notify(){
            $seller_order_code = $this->_post('order_code','','order_code is missing');
            $seller_order = (new SellerOrderLogic())->getInfo(['order_code'=>$seller_order_code]);
            $data=[
                'total_fee'=>$seller_order['info']['price'],
                'out_trade_no' =>$seller_order_code,
                'transaction_id'=>'1112223334445555'
            ];

            $seller_id='111';
            $total_fee = $data['total_fee'];
            $out_trade_no = $data['out_trade_no'];
            $trade_no = $data['transaction_id'];
            $currency = PayCurrency::RMB;
            $payType = 2;
            $notify = (new PaySuccessHook())->success($seller_id,$total_fee,$out_trade_no,$currency,$trade_no,$payType);

            if($notify['info']=='操作成功'){
                $seller_order = (new SellerOrderLogic())->getInfo(['order_code'=>$out_trade_no]);
                $profit = (new ProfitLogic())->getInfo(['order_id'=>$seller_order['info']['id']]);
                $this->apiReturnSuc($profit);
            }
            $this->apiReturnErr($notify);



        }

    /*
     * 用户查询消费记录
     */
    public function queryConsume(){
        $this->checkVersion('100');
        $uid = $this->_post('uid', '', 'uid is missing');
        $page_size = $this->_post('page_size','10');
        $page_index = $this->_post('page_index','1');
        $page = ['curpage'=>$page_index,'size'=>$page_size];
        $result = (new SellerOrderLogic())->queryConsume($uid,$page);
        if($result['status']){
            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr($result['info']);
        }

    }


}